// Created by carolsail

import { StaticInstance } from './../StaticInstance';
import { ENUM_AUDIO_CLIP, ENUM_UI_TYPE } from './../Enum';
import AudioManager from "../manager/AudioManager";
import DataManager from "../manager/DataManager";
import BaseLayer from "./Baselayer";
import ToastManager from '../manager/ToastManager';
import { IRoom } from '../shared/common/types';

const { ccclass, property } = cc._decorator;

@ccclass
export default class RoomJoinLayer extends BaseLayer {

    panel: cc.Node = null
    btnClose: cc.Node = null
    btnSubmit: cc.Node = null
    inputPassword: cc.Node = null

    onLoad() {
        this.panel = cc.find('style/panel', this.node)
        this.btnClose = cc.find('btn_close', this.panel)
        this.btnSubmit = cc.find('btn_submit', this.panel)
        this.btnClose.on('click', this.onCloseClick, this)
        this.btnSubmit.on('click', this.onSubmitClick, this)
        this.inputPassword = cc.find('password', this.panel)
    }

    onDestroy() {
        this.btnClose.off('click', this.onCloseClick, this)
        this.btnSubmit.off('click', this.onSubmitClick, this)
    }

    onEnable() {
        this.zoomIn(this.panel)
    }

    onDisable() { }

    onCloseClick() {
        AudioManager.instance.playSound(ENUM_AUDIO_CLIP.CLICK)
        DataManager.instance.room = null
        StaticInstance.uiManager.toggle(ENUM_UI_TYPE.ROOM_JOIN, false)
        StaticInstance.uiManager.toggle(ENUM_UI_TYPE.HALL)
    }

    async onSubmitClick() {
        AudioManager.instance.playSound(ENUM_AUDIO_CLIP.CLICK)
        const password = this.inputPassword.getComponent(cc.EditBox).string
        // 只允许数字（微信小游戏要求，需做校验）
        const reg = /^[0-9]*$/
        if (reg.test(password)) {
            const item = DataManager.instance.room
            if (password == item.password) {
                const data = await DataManager.instance.wsClient.callApi('RoomJoin', { roomId: item.id, player: DataManager.instance.user })
                if (!data.isSucc) {
                    ToastManager.instance.show(data.err.message, { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })
                    return
                }
                DataManager.instance.room = data.res.room
                StaticInstance.uiManager.toggle(ENUM_UI_TYPE.ROOM_JOIN, false)
                StaticInstance.uiManager.toggle(ENUM_UI_TYPE.ROOM)
            } else {
                ToastManager.instance.show('输入密码有误', { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })
            }
        } else {
            ToastManager.instance.show('密码只允许数字', { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })
        }
    }
}
